package com.example.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.filter.LoginIntercepter;
import com.example.filter.SsoFilter;
import com.example.model.Token;
import com.example.model.User;
import com.example.service.TokenService;
import com.example.service.UserService;
import com.example.util.StringUtil;

@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private TokenService tokenService;
	
	/**
	 * 根据名字或者用户id查询用户
	 */
	@RequestMapping("/getUser")
	public User getUserById(String param) {
		System.out.println("param111="+param);
		User user = userService.getUserByNumOrName(param);
         	
		return user;
	}
	
	/**
	 * 根据名字或者用户id查询用户
	 */
	@RequestMapping("/get")
	public User getUserByName(String name) {
		User user =userService.getUserByNumOrName(name);
		System.out.println("user:"+user);
		return user;
	}
	
	/**
	 * 用户登录
	 */
	@RequestMapping("/login")
	public void login(String username,String password,String requestUrl,
			HttpServletRequest request,HttpServletResponse response) {
		User user =userService.getUserByNumOrName(username);
		Map<String, Object> responseMap=new HashMap<>();
		String tokenEncode="";
		System.out.println("进入登陆username:"+username);
		System.out.println("进入登陆password:"+password);
		System.out.println("进入登陆requestUrl:"+requestUrl);
		try {
		if (user!=null&&user.getPassword().equals(password)) {
			//登陆成功，将登陆状态存到session
			HttpSession session = request.getSession();
			session.setAttribute(SsoFilter.IS_LOGIN, SsoFilter.SSO_LOGIN_STATUS_SUCCESS);
			String expireTime="300";//token过期时间为300秒
			String token =UUID.randomUUID().toString().replaceAll("-", "")+"#"+StringUtil.null2Str(System.currentTimeMillis())+"#"+expireTime;
			System.out.println(token);
			session.setAttribute("token", token);
			session.setAttribute("username", username);
			session.setMaxInactiveInterval(5*60);
			Token tokenModel = new Token();
			tokenModel.setTokenKey(username);
			tokenModel.setTokenValue(token);
			//再将token存入数据库，并把把这个用户之前的token清除  这里用redis其实更方便，设置一个过期时间就可以了
			tokenService.insertToken(tokenModel);
			
			try {
				tokenEncode = URLEncoder.encode(tokenModel.getTokenValue(), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			responseMap.put("token",tokenEncode );
			responseMap.put("success", "success");
			//如果登录成功，本项目请求，使用转发，其他项目使用重定向
		    boolean localFlag=false;
		    if (StringUtil.isBlank(requestUrl)) {
				localFlag=true;
				requestUrl="/successLogin";
			}
		    if (requestUrl.indexOf(LoginIntercepter.LOCAL_URL)!=-1||!requestUrl.startsWith("http://")) {
				localFlag=true;
			}
			
			
				System.out.println("sso server登录成功，重定向登录原地址");
				if (localFlag) {
					request.getRequestDispatcher(requestUrl+"?token="+tokenEncode).forward(request, response);
				}else {
					response.sendRedirect(requestUrl+"?token="+tokenEncode);
				}
				return;
			
		}else {
			request.getRequestDispatcher("/indexLogin").forward(request, response);
		}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 注销登录
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,String token) {
		System.out.println("注销登录");
		System.out.println("token:"+token);
		Token token2 = new Token();
		token2.setTokenValue(token);
		tokenService.logoutToken(token2);
		request.getSession().invalidate();
		
		return "success";
	}
	

}
